<?php

namespace App\Tools;


class Image
{
    /**
     * 图片原比例生成缩略图
     * @param $img_src  // 图像路径
     * @param $resize_width // 新宽
     * @param $resize_height // 新高
     */
    public static function resizeImage($img_src, $resize_width, $resize_height)
    {
        //图片的类型
        $type = substr(strrchr($img_src, "."), 0);
        $path = substr($img_src, 0, strrpos($img_src, ".")) . "_{$resize_width}x{$resize_height}" . $type;
        //初始化图象
        if ($type == ".jpg" || $type == ".jpeg") {
            $im = imagecreatefromjpeg($img_src);
        }
        if ($type == ".png") {
            $im = imagecreatefrompng($img_src);
        }

        if (!isset($im)) return result_json(409, '图片无效');

        $width = imagesx($im);
        $height = imagesy($im);

        //生成图象
        //改变后的图象的比例
        $resize_ratio = ($resize_width) / ($resize_height);
        //实际图象的比例
        $ratio = ($width) / ($height);

        if ($ratio >= $resize_ratio) {
            $newimg = imagecreatetruecolor($resize_width, ($resize_width) / $ratio);
            if(function_exists('imagecopyresampled')) {
                imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height);
            } else {
                imagecopyresized($newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height);
            }
            imagejpeg($newimg, $path);
        }
        if ($ratio < $resize_ratio) {
            $newimg = imagecreatetruecolor(($resize_height) * $ratio, $resize_height);
            if(function_exists(“ImageCopyResampled”)) {
                imagecopyresampled($newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height);
            } else {
                imagecopyresized($newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height);
            }
            imagejpeg($newimg, $path);
        }
        ImageDestroy($im);
        if (!is_file($path)) return result_json(500, '上传失败');
        return result_json(200, '成功', ['file_path' => $path]);
    }
}
